package com.yc.multiple.jpa.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryOrder",
        transactionManagerRef = "transactionManagerOrder",
        basePackages = {"com.yc.multiple.jpa.dao.order"}
)
@EnableTransactionManagement
public class OrderDataSourceConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Bean
    @ConfigurationProperties("spring.datasource.order")
    public DataSource orderDataSource(){
        return new HikariDataSource();
    }


    @Bean(name = "entityManagerFactoryOrder")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryOrder(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = builder
                .dataSource(orderDataSource())
                //设置实体类所在位置
                .packages("com.yc.multiple.jpa.bean.order")
                .persistenceUnit("orderPersistenceUnit")
                .properties(jpaProperties.getProperties())
                .build();
        return entityManagerFactory;
    }


    @Bean(name = "transactionManagerOrder")
    public PlatformTransactionManager transactionManagerOrder(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryOrder(builder).getObject());
    }
}
